package ro.ubbcluj.cs.damate.services;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ro.ubbcluj.cs.damate.persistence.entities.Group;
import ro.ubbcluj.cs.damate.persistence.entities.User;
import ro.ubbcluj.cs.damate.persistence.repository.UserRepository;

import java.util.List;

/**
 * @author Lóránd Fazakas (lorand)
 *         Date: 5/10/12
 *         Time: 9:49 PM
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Transactional
    public void create(User transientUser) {
        userRepository.save(transientUser);
    }

    @Transactional
    public void update(User persistentUser) {
        userRepository.save(persistentUser);
    }

    @Transactional
    public void delete(User persistentUser) {
        userRepository.delete(persistentUser);
    }

    public User findByUsername(String username) {
        return userRepository.findOne(username);
    }

    public List<User> findAll() {
        return userRepository.findAllUsers();
    }

    public List<User> findAllByState(Boolean active) {
        return userRepository.findByState(active);
    }

    public List<User> findAllByGroup(Group group) {
        return userRepository.findByGroup(group);
    }

    public User findByUsernameAndPassword(String username, String password) {
        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
            List<User> users = userRepository.findByUsernameAndPassword(username, password);
            if (users != null && !users.isEmpty()) {
                return users.get(0);
            }
        }
        return null;
    }
}
